package com.moneywelcome.orderassembly.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.moneywelcome.orderassembly.model.GoldPrice;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class GoldUtil {
    public static void main(String[] args) throws IOException {
        System.out.println(getCurrentPrice("1053"));
    }
    public static GoldPrice getCurrentPrice(String goldId) throws IOException {
        URL u = new URL("http://api.k780.com/?app=finance.gold_price&goldid=" + goldId + "&appkey=63711&sign=8b02b2d90b386bc2e9e3b117436e5ba5&format=json");
        InputStream in = u.openStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte buf[] = new byte[1024];
            int read = 0;
            while ((read = in.read(buf)) > 0) {
                out.write(buf, 0, read);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        byte b[] = out.toByteArray();
        String result = new String(b, "utf-8");
        result = result.substring(result.lastIndexOf("{"), result.indexOf("}") + 1);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        GoldPrice goldPrice = new GoldPrice();
        System.out.println(jsonObject);
        goldPrice.setLastPrice(Double.valueOf(jsonObject.getStr("last_price")));
        goldPrice.setYesyPrice(Double.valueOf(jsonObject.getStr("yesy_price")));
        return goldPrice;
    }
}
